import { useCallback, useRef, useState } from "react";
import Dialog from "~/components/Dialog";
import Thinking from "../components/Thinking";

import { api } from "~/utils/api";

export default function Chat() {
  const [inputValue, setInputValue] = useState('');
  const [messages, setMessages] = useState<Message[]>([
  ]);

  const container = useRef<HTMLDivElement>({} as HTMLDivElement);

  const scrollIntoView = useCallback(() => setTimeout(() => container.current.scrollIntoView(false), 20), []);

  const { mutate, isLoading } = api.chatgpt.chat.useMutation({
    onSuccess(data) {
      const msg = data.result.choices[0]!.message as any;
      setMessages([...messages, msg]);
      scrollIntoView();
    }
  });

  async function send() {
    console.log(inputValue, container.current);
    const content = inputValue;
    const msgs = [...messages, { role: 'user', content } as Message];
    setMessages(msgs);
    setInputValue('');
    mutate(msgs);
    scrollIntoView();
  }
  return (
    <div className="bg-gray-800">
      <div className="mx-auto p-4 container bg-gray-900 max-w-[700px] flex-col h-screen flex">
        <div className="text-center py-4 text-6xl font-bold bg-gradient-to-r from-green-600 to-purple-600 text-transparent bg-clip-text">ChatGPT</div>
        <div className=" overflow-auto p-6 flex-grow">
          <div ref={container} className="flex flex-col space-y-2">
            {
              messages.map((message, index) => <Dialog key={index} message={message} />)
            }
            {
              isLoading && <Thinking />
            }
          </div>
        </div>
        <div className="flex mt-2 rounded-lg border border-gray-700 bg-gray-800">
          <input placeholder="请输入文字..." className="flex-grow px-4 py-2 text-white focus:outline-none bg-transparent" value={inputValue}
            onChange={e => setInputValue(e.target.value)}
            onKeyDown={e => {
              if (e.key === 'Enter')
                send();
            }}
          />
          <button onClick={send} className=" bg-purple-500 rounded-lg px-4 py-2 text-white font-semibold focus:outline-none hover:bg-purple-600 transition-colors duration-300">发送</button>
        </div>
      </div>
    </div>
  );
};;